# encoding:utf-8
"""
Author: gallopingvijay
Email: 1937832819@qq.com
Website: https://www.choudalao.com
Document:https://ai.baidu.com/ai-doc/OCR/1k3h7y3db
ApplyFor:https://console.bce.baidu.com/ai/?_=1619449427519&fromai=1#/ai/ocr/app/list
"""
import requests
import base64
import os
import yaml

CLIENT_ID = ''
CLIENT_SECRET = ''


class BaiduImg():
    def __init__(self):
        # 配置
        self.configs = self.get_config()
        global CLIENT_ID
        global CLIENT_SECRET
        CLIENT_ID = self.configs['baidu_img']['CLIENT_ID']
        CLIENT_SECRET = self.configs['baidu_img']['CLIENT_SECRET']
        self.base_url = self.configs['baidu_img']['BASE_URL']
        self.token = ''

    def dealImg(self, path, type=1):
        self.getToken()
        if type == 1:
            # 通用文字识别
            request_url = self.base_url + "/rest/2.0/ocr/v1/general_basic"
        elif type == 2:
            # 位置信息版
            request_url = self.base_url + "/rest/2.0/ocr/v1/general"
        elif type == 3:
            request_url = self.base_url + "/rest/2.0/ocr/v1/accurate_basic"
        elif type == 4:
            request_url = self.base_url + "/rest/2.0/ocr/v1/accurate"
        else:
            request_url = self.base_url + "/rest/2.0/ocr/v1/general_basic"

        if isinstance(path, bytes):
            s = path
        else:
            # 二进制方式打开图片文件
            f = open(path, 'rb')
            s = f.read()
        img = base64.b64encode(s)
        params = {"image": img}
        access_token = self.token
        request_url = request_url + "?access_token=" + access_token
        headers = {'content-type': 'application/x-www-form-urlencoded'}
        response = requests.post(request_url, data=params, headers=headers)
        if response:
            res = response.json()
            if 'error_msg' in res:
                return res['error_msg']
            else:
                return res['words_result'][0]['words']

    def getToken(self):
        # client_id 为官网获取的AK， client_secret 为官网获取的SK
        host = self.base_url + '/oauth/2.0/token?grant_type=client_credentials&client_id=' + str(
            CLIENT_ID) + '&client_secret=' + str(CLIENT_SECRET)
        response = requests.get(host)
        if response:
            data = response.json()
            self.token = data['access_token']
            print(data['access_token'])
            # return data['access_token']

    def get_config(self):
        '''
        获取config.yaml配置
        :return:configs
        '''
        # 获取当前文件的上级Realpath
        fileNamePath = os.path.abspath(
            os.path.dirname(os.path.dirname(__file__)))
        # 读取文件
        yamlPath = os.path.join(fileNamePath, 'config.yaml')
        # 加上 ,encoding='utf-8'，处理配置文件中含中文出现乱码的情况。
        file = open(yamlPath, 'r', encoding='utf-8')
        # 读取文件
        cont = file.read()
        # 返回配置
        return yaml.safe_load(cont)

    def test(self):
        print(11)


# if __name__ == '__main__':
#     path = '../code_img/veriCode (1).do'
#     baidu = BaiduImg()
#     res = baidu.dealImg(path, 3)
#     print(res)
